<?php

namespace App\Http\Controllers\Entry;

use App\Http\Controllers\Component\MasterResponseController;
use App\Http\Requests\Entry\LoginRequest;
use Auth;
use Cache;
use Cookie;
use Illuminate\Http\Request;


class LoginController extends MasterResponseController
{


    public function loginForm()
    {
        if (Auth::check()){
            Cache::put('unlogout',true,60);
            return redirect('/user');
        }
        return view('entry.login');
    }

    //登录处理
    public function login(LoginRequest $request)
    {
        $data = $request->all();
        $status = Auth::attempt([
            'email' => $data['email'],
            'password' => $data['password'],
        ]);
        if ($status) {
            $loginToken = Cache::get('STRING_SINGLETOKEN_' . Auth::user()->id);
            //如果此用户的loginToken还存在Cache中  说明用户在此前已经登录 且尚未未退出登录
            if ($loginToken) {
                //退出用户在其他地方的登录 //使当前用户在其他地方登录的会话失效
                Auth::logoutOtherDevices($data['password']);
            }
            //登录成功  制作 token
            // md5加密 用户客户机IP 用户id 登录时间
            $loginToken = md5($request->getClientIp() . Auth::user()->id . time());
            // 当前 loginToken 存入 Redis 120分钟 key为 [STRING_SINGLETOKEN_用户id]
            Cache::put('STRING_SINGLETOKEN_' . Auth::user()->id, $loginToken, 60 * 120);
            return parent::success('登录成功！,1秒后将跳转到首页');
        }
        return parent::error('邮箱或密码错误');
    }

    public function logout(Request $request)
    {
        $this->middleware('unlogin');
        Cache::forget('STRING_SINGLETOKEN_' . Auth::user()->id);
        Auth::guard('web')->logout();
        //清空当前Session
        $request->session()->flush();
        return redirect('/entry/login');
    }
}
